<template>
  <div class="flex items-center mb-4">
    <div class="header-title mr-2">报关信息</div>
    <el-button
      class="ml-2"
      v-if="type == 'product' && handleType != 'view'"
      @click="handleCustomsSearch"
      >报关信息查询</el-button
    >
    <slot name="handle"></slot>
  </div>
  <el-form
    ref="formRef"
    :model="form"
    label-align="right"
    label-width="120"
    size="default"
    :label-position="handleType == 'view' ? 'left' : 'top'"
    :class="handleType == 'view' ? 'view' : ''"
  >
    <template v-if="handleType == 'view'">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="中文报关名称:">
            {{ form.cn_name }}
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="英文报关名称:">
            {{ form.en_name }}
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="产品用途:">
            {{ form.purpose }}
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="海关编码:">
            {{ form.customs_code }}
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="中文报关材质:">
            {{ form.cn_material }}
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="英文报关材质:">
            {{ form.en_material }}
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="报关单位:">
            {{ form.declare_unit }}
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="规格数量:">
            {{ form.customs_quantity }}
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="退税率:"> {{ form.tax_rebate_rate }}% </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="电池信息:">
            电池类型：{{ computeBatteryName(form.battery_type) }} 电池电压：{{
              form.battery_voltage
            }}
            {{ form.battery_voltage_unit }} 电池容量：{{ form.battery_capacity
            }}{{ form.battery_capacity_unit }}</el-form-item
          >
        </el-col>
        <el-col :span="24">
          <el-form-item label="清关信息:">
            <el-button v-if="form.is_multi_platform == 1">多平台/站点售卖</el-button>
          </el-form-item>
          <el-table :data="form.goods_sku_customs_info" border>
            <el-table-column prop="platform_name" label="平台" width="100">
            </el-table-column>
            <el-table-column prop="country_name" label="国家" width="120">
            </el-table-column>
            <el-table-column prop="customs_price" label="链接销售价" width="100">
              <template #default="{ row }">
                {{ row.customs_price }} {{ row.customs_currency }}
              </template>
            </el-table-column>
            <el-table-column prop="clearance_price" label="海关价格(30%)" width="120">
              <template #default="{ row }">
                {{ row.clearance_price }} {{ row.customs_currency }}
              </template>
            </el-table-column>
            <el-table-column prop="customs_link" label="销售链接">
              <template #default="{ row }">
                <VText
                  type="button"
                  :line="2"
                  :value="row.customs_link"
                  :copy="true"
                  @click="openLink(row.customs_link)"
                ></VText>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="24">
          <el-form-item label="申报要素维护项:"> </el-form-item>
          <el-table :data="form.declare_elements_list" border>
            <el-table-column label="序号" width="100">
              <template #default="{ row, $index }">
                {{ $index }}
              </template>
            </el-table-column>
            <el-table-column prop="text" label="维护项"> </el-table-column>
            <el-table-column prop="value" label="维护内容"> </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="24">
          <el-form-item label="申报要素:"> </el-form-item>
          <el-input
            v-model="form.declare_elements"
            :autosize="{ minRows: 4, maxRows: 10 }"
            placeholder="请输入"
            type="textarea"
            readonly
          />
        </el-col>
      </el-row>
    </template>
    <template v-else>
      <el-row :gutter="20">
        <el-col :span="24" class="flex items-center">
          <el-form-item label="中文报关名称" required class="flex-auto flex-shrink-0">
            <el-tooltip
              class="item"
              effect="dark"
              placement="top"
              :content="order_exist.content"
              :disabled="!order_exist.exist"
            >
              <el-input
                v-model="form.cn_name"
                placeholder="名称"
                class="w-full"
                :disabled="order_exist.exist"
              />
            </el-tooltip>
          </el-form-item>
          <el-button class="mx-4 mt-2" @click="translate(form.cn_name, 'en_name')" link>
            <svg-icon class="base-text-color w-4 h-4" icon-class="fanyi"
          /></el-button>
          <el-form-item
            label="英文报关名称"
            required
            class="flex-auto flex-shrink-0 ml-2"
          >
            <el-input v-model="form.en_name" placeholder="名称" class="w-full" />
          </el-form-item>
        </el-col>
        <div class="text-[#999] text-xs mt-1 ml-2" v-if="tooltip.cn_name">
          提示：{{ tooltip.cn_name }}
        </div>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24" class="flex items-center relative">
          <div class="absolute top-[-12px] left-[400px] flex" v-if="info.is_dangerous">
            <img
              class="w-[40px] h-[40px] mr-1"
              src="https://xc-goods.oss-cn-shenzhen.aliyuncs.com/20240515/data/Company/%28wei%29%2B045240188d69d8949e163fd84c2a5da50138df308.png"
            />
          </div>
          <el-form-item label="中文报关材质" required class="flex-auto flex-shrink-0">
            <el-input v-model="form.cn_material" placeholder="材质" />
          </el-form-item>
          <el-button
            class="mx-4 mt-2"
            @click="translate(form.cn_material, 'en_material')"
            link
          >
            <svg-icon class="base-text-color w-4 h-4" icon-class="fanyi"
          /></el-button>
          <el-form-item
            label="英文报关材质"
            required
            class="flex-auto flex-shrink-0 ml-2"
          >
            <el-input v-model="form.en_material" placeholder="材质" />
          </el-form-item>
        </el-col>
        <div class="text-[#999] text-xs mt-1 ml-2" v-if="tooltip.cn_material">
          提示：{{ tooltip.cn_material }}
        </div>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="海关编码" required>
            <template #label>
              <span>海关编码 </span>
              <el-tooltip
                class="item"
                effect="dark"
                placement="top"
                :content="order_exist.content"
                :disabled="!order_exist.exist"
              >
                <el-button
                  class="absolute -top-1 left-[180px]"
                  type="primary"
                  size="small"
                  @click="handleDeclareElements()"
                  :disabled="order_exist.exist"
                >
                  申报要素维护项查询</el-button
                >
              </el-tooltip>
              <el-button
                class="absolute -top-1 left-[310px]"
                size="small"
                @click="checkCode(form.customs_code)"
                >跳转查询海关编码</el-button
              >
            </template>
            <el-tooltip
              class="item"
              effect="dark"
              placement="top"
              :content="order_exist.content"
              :disabled="!order_exist.exist"
            >
              <SelectCustomsCode
                class="w-full"
                v-model="form.customs_code"
                placeholder="编码"
                :disabled="order_exist.exist"
                @changeItem="changeDeclareElements"
              ></SelectCustomsCode>
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="报关单位" required>
                <el-tooltip
                  class="item"
                  effect="dark"
                  placement="top"
                  :content="order_exist.content"
                  :disabled="!order_exist.exist"
                >
                  <el-input
                    v-model.trim="form.declare_unit"
                    placeholder="例如：个、套、台"
                    :disabled="order_exist.exist"
                  />
                </el-tooltip>
                <div class="text-[#999] text-xs mt-1" v-if="tooltip.declare_unit">
                  提示：{{ tooltip.declare_unit }}
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="规格数量" required>
                <el-tooltip
                  class="item"
                  effect="dark"
                  placement="top"
                  :content="order_exist.content"
                  :disabled="!order_exist.exist"
                >
                  <el-input
                    v-model.number="form.customs_quantity"
                    placeholder="请输入"
                    :min="1"
                    :disabled="order_exist.exist"
                  />
                </el-tooltip>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="产品用途" required>
            <el-input v-model="form.purpose" placeholder="用途" />
            <div class="text-[#999] text-xs mt-1" v-if="tooltip.purpose">
              提示：{{ tooltip.purpose }}
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="退税率" required>
            <el-tooltip
              class="item"
              effect="dark"
              placement="top"
              :content="order_exist.content"
              :disabled="!order_exist.exist"
            >
              <el-input
                v-model.trim="form.tax_rebate_rate"
                placeholder="输入"
                :disabled="order_exist.exist"
                @blur="blurTaxRate"
                oninput="value=value.replace(/[^\d.]/g,'').replace(/^(\d*\.?\d{0,2}).*/,'$1')"
              >
                <template #append>
                  <el-button type="primary">%</el-button>
                </template>
              </el-input>
            </el-tooltip>
            <div class="text-[#999] text-xs mt-1" v-if="tooltip.tax_rebate_rate_text">
              提示：{{ tooltip.tax_rebate_rate_text }}
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="电池信息">
            <div class="flex">
              <el-select
                v-model="form.battery_type"
                style="width: 200px"
                placeholder="电池类型选择"
                clearable
                filterable
              >
                <el-option
                  v-for="i in options['goods.GoodsSkuCustom']?.[0].batteryTypeText"
                  :key="i.value"
                  :label="i.label"
                  :value="i.value"
                />
              </el-select>
              <el-input
                style="width: 200px"
                v-model="form.battery_voltage"
                placeholder="电池电压"
                clearable
                oninput="value=value.replace(/[^\d.]/g,'').replace(/^(\d*\.?\d{0,2}).*/,'$1')"
              />
              <el-select
                style="width: 80px"
                v-model="form.battery_voltage_unit"
                placeholder="V"
                clearable
                filterable
              >
                <el-option
                  v-for="i in voltageOptions"
                  :key="i.value"
                  :label="i.label"
                  :value="i.value"
                />
              </el-select>
              <el-input
                style="width: 200px"
                v-model="form.battery_capacity"
                placeholder="电池容量"
                clearable
                oninput="value=value.replace(/[^\d.]/g,'').replace(/^(\d*\.?\d{0,2}).*/,'$1')"
              />
              <el-select
                style="width: 80px"
                v-model="form.battery_capacity_unit"
                placeholder="mAh"
                clearable
                filterable
              >
                <el-option
                  v-for="i in capacitanceOptions"
                  :key="i.value"
                  :label="i.label"
                  :value="i.value"
                />
              </el-select>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="是否多平台/国家售卖" required>
            <el-radio-group v-model="form.is_multi_platform" class="ml-4">
              <el-radio
                v-for="(item, index) in whetherOptions"
                :key="index"
                :label="item.value"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="清关信息" required>
            <template #label>
              <span>清关信息 </span>
              <el-button
                v-if="type == 'product'"
                type="primary"
                size="small"
                text
                @click="handldSyncPlatformSite"
                >同步推荐平台/站点
              </el-button>
            </template>
            <template v-for="(item, index) in form.goods_sku_customs_info" :key="index">
              <div class="flex mb-2" v-if="!item.delete">
                <SelectPlatform
                  class="w-[90px] mr-2"
                  v-model="item.platform_id"
                  placeholder="平台"
                  @change="changePlatformName($event, item)"
                ></SelectPlatform>
                <el-select
                  class="w-[90px] mr-2"
                  v-model="item.country_id"
                  placeholder="国家"
                  @change="changeName($event, item)"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="i in countryOptions"
                    :key="i.id"
                    :label="i.name"
                    :value="i.id"
                  />
                </el-select>
                <el-input
                  class="mr-2"
                  style="width: 90px"
                  v-model.trim="item.clearance_number"
                  @blur="calculatePrice(item)"
                  placeholder="清关编码"
                >
                </el-input>
                <el-input
                  class="mr-2"
                  style="width: 90px"
                  v-model.trim="item.customs_price"
                  @blur="calculatePrice(item)"
                  placeholder="销售价格"
                >
                </el-input>
                <el-input
                  class="mr-2"
                  style="width: 90px"
                  v-model.trim="item.clearance_price"
                  placeholder="清关价格"
                  disabled
                >
                </el-input>

                <SelectCurrency
                  class="w-[90px] mr-2"
                  v-model="item.customs_currency"
                  placeholder="币种"
                ></SelectCurrency>

                <el-input
                  class="mr-2"
                  style="width: 300px"
                  v-model="item.customs_link"
                  placeholder="报关链接"
                >
                  <template #append>
                    <el-button
                      style="background: #3487ff; color: #ffffff"
                      type="primary"
                      @click="getPublicationLink(item)"
                      >获取刊登链接</el-button
                    >
                  </template>
                </el-input>
                <div class="w-20 flex">
                  <svg-icon
                    class="w-4 mt-2 icon icon-color"
                    icon-class="add03"
                    @click="addArray"
                  />
                  <svg-icon
                    class="w-4 mt-2 icon mr-3 ml-3"
                    icon-class="jian"
                    @click="deleteArray(item, index)"
                  />
                </div>
              </div>
            </template>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item class="w-full" label="申报要素维护项" required>
        <template #label>
          <span>申报要素维护项</span>
          <el-tooltip
            class="item"
            effect="dark"
            placement="top"
            :content="order_exist.content"
            :disabled="!order_exist.exist"
          >
            <el-button
              :disabled="order_exist.exist"
              type="primary"
              size="small"
              class="ml-2"
              @click="handleUpdate()"
              >更新</el-button
            >
          </el-tooltip>
        </template>
        <div
          class="flex w-full"
          v-for="(item, index) in form.declare_elements_list"
          :key="index"
        >
          <div class="w-[60px] h-[34px] border text-center">{{ index }}</div>
          <div class="flex w-[800px]">
            <el-input
              v-model="item.text"
              placeholder="请输入维护项"
              :disabled="item.disabled || order_exist.exist"
              style="width: 500px"
              @input="inputChange($event, item)"
            ></el-input>
            <el-input
              v-model="item.value"
              :disabled="item.readonly || order_exist.exist"
              placeholder="请输入"
              style="width: 300px"
            ></el-input>
          </div>
          <div class="w-20 flex ml-2">
            <svg-icon
              class="w-4 mt-2 icon icon-color"
              @click="handleCreate(item)"
              icon-class="add03"
            />
            <svg-icon
              class="w-4 mt-2 icon mr-3 ml-3"
              @click="handleDelete(item, index)"
              icon-class="jian"
            />
          </div>
        </div>
      </el-form-item>
      <el-form-item label="申报要素">
        <el-input
          v-model="form.declare_elements"
          :autosize="{ minRows: 4, maxRows: 10 }"
          placeholder="请输入"
          type="textarea"
          disabled
        />
      </el-form-item>
    </template>
  </el-form>
  <CustomsList
    ref="CustomsListRef"
    :supplier_name="info.supplier_name"
    @select="selectCustoms"
  ></CustomsList>
</template>
<script setup name="customInfo">
import { reactive, toRefs } from "vue";
import { translation, getMinPriceBySku, getAmazonPrice } from "@/api/index";
import SelectCurrency from "@/components/SelectCurrency";
import { filterDeleteFlag } from "@/utils/index.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { getCustomsDetail, getCountryCurrency } from "@/api/index";
import { getBrandList, getplatformSite } from "./api.js";
import { whetherOptions, voltageOptions, capacitanceOptions } from "./data.js";
import SelectPlatform from "@/components/SelectPlatform";
import { openLink, debounce } from "@/utils/index.js";
import { getOptions } from "@/api/index.js";
import CustomsList from "./CustomsList.vue";
import { matchingMaintenanceFormat } from "@/utils/customs.js";
import SelectCustomsCode from "./components/SelectCustomsCode/index.vue";

let formData = reactive(inject("form")) || null;

const emit = defineEmits(["update:modelValue"]);
const props = defineProps({
  modelValue: {
    type: Object,
    default: () => {
      return {};
    },
  },
  info: {
    type: Object,
    default: () => {
      return {};
    },
  },
  order_exist: {
    type: Object,
    default: () => {
      return {};
    },
  },
  handleType: {
    type: String,
    default: "edit",
  },
  skuIndex: {
    type: Number,
    default: 0,
  },
  type: {
    type: String,
    default: "product",
  },
});

const { info, handleType, skuIndex, order_exist } = toRefs(props);

const data = reactive({
  tooltip: {},
  countryOptions: [],
  options: {},
});

const { tooltip, countryOptions, options } = toRefs(data);

const form = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emit("update:modelValue", val);
  },
});

const formRef = ref();

// 翻译
const translate = (val, field) => {
  if (!val) return false;
  let param = {
    target_lang: "en",
    text: val,
    use_proxy: true,
  };
  translation(param)
    .then((res) => {
      form.value[field] = res.data;
      ElMessage.success("翻译成功");
    })
    .catch(() => {
      ElMessage.success("翻译失败");
    });
};

const checkCode = (code) => {
  if (code) {
    window.open(`http://www.hsbianma.com/search?keywords=${code}`, "_blank");
  } else {
    window.open("http://www.hsbianma.com/Home/Message", "_blank");
  }
};

const addArray = () => {
  form.value.goods_sku_customs_info.push({
    customs_currency: "USD",
  });
};

const deleteArray = (item, index) => {
  if (canDeleteAllWithoutDeleteFlag()) {
    ElMessage.error("至少保留一条");
    return;
  }
  if (item.id) {
    item.delete = 1;
  } else {
    form.value.goods_sku_customs_info.splice(index, 1);
  }
};

const canDeleteAllWithoutDeleteFlag = () => {
  const nonDeletedItems = form.value.goods_sku_customs_info.filter(
    (item) => !("delete" in item) || item.delete !== 1
  );
  return nonDeletedItems.length === 1;
};

// 新增
const handleCreate = (item) => {
  if (order_exist.value.exist) {
    return ElMessage.warning(order_exist.value.content);
  }

  if (item.disabled) {
    return ElMessage.warning("查询后申报要素维护项不支持添加，删除");
  }
  if (form.value.declare_elements_list.length == 20) {
    return ElMessage.warning("最多只能添加20条数据");
  }
  form.value.declare_elements_list.push({});
};

// 删除
const handleDelete = (item, index) => {
  if (order_exist.value.exist) {
    return ElMessage.warning(order_exist.value.content);
  }

  if (item.disabled) {
    return ElMessage.warning("查询后申报要素维护项不支持添加，删除");
  }
  if (filterDeleteFlag(form.value.declare_elements_list)) {
    ElMessage.error("至少保留一条");
    return;
  }
  form.value.declare_elements_list.splice(index, 1);
};

const changeDeclareElements = async (val) => {
  // if (!val) return;
  if (val.declare_elements_list?.length) {
    ElMessageBox.confirm("获取新的申报要素，是否覆盖当前申报要素维护项", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        form.value.declare_elements_list = val.declare_elements_list.map((i) => {
          i.disabled = true;
          return i;
        });
        tooltip.value.cn_name = val.goods_name;
        tooltip.value.declare_unit = val.code_unit;
        form.value.tax_rebate_rate = val.refund_tax_rate;
        tooltip.value.tax_rebate_rate = val.refund_tax_rate;
        handleUpdate();
      })
      .catch(async () => {});
  } else {
    ElMessageBox.confirm("暂无查询到相关信息，是否切换手动维护申报要素维护项", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        form.value.declare_elements_list = [
          {
            text: "",
          },
        ];
      })
      .catch(async () => {});
  }
};

let throttleTimer;
const handleDeclareElements = async () => {
  if (throttleTimer) {
    return;
  }

  throttleTimer = setTimeout(() => {
    throttleTimer = null;
  }, 500);

  if (!form.value.customs_code) {
    return ElMessage.error("请输入海关编码");
  }
  try {
    const res = await getCustomsDetail({
      customs_goods_code: form.value.customs_code,
    });
    changeDeclareElements(res.data);
  } catch (e) {
    console.error(e);
  }
};

const handleUpdate = () => {
  form.value.declare_elements_list.forEach(async (item, index) => {
    if (item.text) {
      const text = await getValue(item.text, item.value);
      item.value = text;
      const shouldDisable =
        [KEYWORDS.brandType, KEYWORDS.exportBenefit, KEYWORDS.brand, KEYWORDS.model].some(
          (keyword) => item.value !== "" && item.text.includes(keyword)
        ) && !item.text.includes(KEYWORDS.unknownBrand);
      item.readonly = shouldDisable;
      if (!shouldDisable) {
        item.readonly = false;
      }
    }
  });
};

// 定义关键字常量
const KEYWORDS = {
  material: "材质",
  purpose: "用途",
  supplierName: [
    "厂家名称",
    "注册厂商",
    "生产厂商",
    "生产商名称（英文全称）",
    "厂商（中文或外文名称）",
  ],
  brandType: "品牌类型",
  exportBenefit: "出口享惠情况",
  unknownBrand: "××品牌",
  brand: "品牌",
  model: "型号",
};

const getValue = async (val, value = "") => {
  const format = (await matchingMaintenanceFormat(val)) || "";

  switch (true) {
    case val.includes(KEYWORDS.material):
      tooltip.value.cn_material = val || value || "";
      return format + (form.value.cn_material || "");
    case val.includes(KEYWORDS.purpose):
      tooltip.value.purpose = val;
      const purpose = form.value.purpose || "";
      return format + purpose || value;
    case KEYWORDS.supplierName.some((keyword) => val.includes(keyword)):
      if (isEnglishOrNumeric(info.value.supplier_name)) {
        return format + value;
      } else {
        return format + info.value.supplier_name || value;
      }
    case val.includes(KEYWORDS.brandType):
      console.log(val);

      const res = await fetchBrandCustomsType(info.value.brand_name)
        .then((customsType) => {
          return customsType || "0";
        })
        .catch((error) => {
          console.error("Fetch failed:", error);
        });
      return format + res || value || "0";
    case val.includes(KEYWORDS.exportBenefit):
      return format + "0";
    case val.includes(KEYWORDS.unknownBrand):
      return format + value;
    case val.includes(KEYWORDS.brand):
      const brand_name = info.value.brand_name || "无";
      const brand_name_text = brand_name;
      console.log(brand_name_text);
      return format + brand_name_text || value;
    case val.includes(KEYWORDS.model):
      const specification_model = formData.value.specification_model || "无";
      const specification_model_text = specification_model;
      return format + specification_model_text || value;
    default:
      return format + value || ""; // 明确未匹配情况的返回值
  }
};

async function fetchBrandCustomsType(name) {
  if (!name) {
    return "";
  }
  try {
    const res = await getBrandList({ name });
    if (res.data.length > 0) {
      return res.data[0].customs_type;
    } else {
      // 显式处理未找到数据的情况
      return ""; // 或者其他默认值
    }
  } catch (error) {
    console.error("Error fetching brand list:", error);
    throw error; // 重新抛出错误，以便在调用此函数的地方可以处理
  }
}

const initComponent = () => {
  tooltip.value = {};
};

const validate = () => {
  return formRef.value.validate();
};

defineExpose({ initComponent, validate });

const blurTaxRate = () => {
  if (Number(tooltip.value.tax_rebate_rate) > 0) {
    if (Number(tooltip.value.tax_rebate_rate) != Number(form.value.tax_rebate_rate)) {
      tooltip.value.tax_rebate_rate_text =
        "填写的退税率与海关编码信息中的数据不一致，请确认！！";
    } else {
      tooltip.value.tax_rebate_rate_text = "";
    }
  }
};

// 是否英文、数字
const isEnglishOrNumeric = (val) => {
  const pattern = /^[A-Za-z0-9]+$/;
  return pattern.test(val);
};

// 国家名称
const changeName = (val, item) => {
  const find = countryOptions.value.find((i) => i.id == val);
  if (find) {
    item.country_name = find?.name;
    item.customs_currency = find?.base_currencys?.currency || "USD";
  } else {
    item.country_name = "";
  }
};

// 平台名称
const changePlatformName = (val, item) => {
  item.platform_name = val;
  if (val == "ebay") {
    item.country_id = 8;
  } else if (val == "amazon") {
    item.country_id = 262;
  }
  changeName(item.country_id, item);
};

// 计算清关价格
const calculatePrice = (item) => {
  item.clearance_price = (Number(item.customs_price || 0) * 0.3).toFixed(2);
  return;
};

// 提交
const countryMap = new Map([
  ["德国", "DE"],
  ["英国", "UK"],
  ["澳大利亚", "AU"],
  ["美国", "US"],
]);

// 获取获取刊登链接
const getPublicationLink = async (item) => {
  if (!item.country_name) {
    return ElMessage.error("请选择国家");
  }
  if (!info.value.sku) {
    ElMessage.warning("未查询到Lishing链接，请手动维护。");
    return;
  }
  const countryArray = [countryMap.get(item.country_name)];
  let requests = [];

  // 根据条件添加请求

  const platformData = { sku: info.value.sku, countryArray };
  if (["ebay"].includes(item.platform_name) || !item.platform_name) {
    requests.push(getEbay(platformData));
  }
  if (["amazon"].includes(item.platform_name) || !item.platform_name) {
    requests.push(getAmazon(platformData));
  }

  // 如果有请求，等待所有请求完成
  if (requests.length > 0) {
    try {
      const responses = await Promise.all(requests);
      const minPrice = await handleData(responses);
      if (!minPrice) {
        ElMessage.warning("未查询到Lishing链接，请手动维护。");
        return;
      }
      item.customs_link = minPrice?.customs_link;
      item.currency = minPrice?.currency;
      item.customs_price = minPrice?.customs_price;
      item.clearance_price = minPrice?.clearance_price;
    } catch (error) {
      console.error("请求失败:", error);
      ElMessage.error("请求失败，请稍后再试");
    }
  } else {
    console.log("无需发送请求");
  }
};
// 获取ebay价格信息
const getEbay = async (data) => {
  try {
    const res = await getMinPriceBySku(data);
    if (res.data.length) {
      const list = res.data.map((i) => {
        return {
          customs_link: i.itemUrl,
          currency: i.currency,
          customs_price: i.minPrice,
          clearance_price: (Number(i.minPrice) * 0.3).toFixed(2),
          country: i.country,
        };
      });
      return list;
    }
    return res.data;
  } catch (e) {
    throw Error(e);
  }
};

// 获取亚马逊价格信息
const getAmazon = async (data) => {
  try {
    const res = await getAmazonPrice(data);
    if (res.data.length) {
      const list = res.data.map((i) => {
        return {
          customs_link: i.asin_url,
          currency: i.currency,
          customs_price: i.price,
          clearance_price: (Number(i.price) * 0.3).toFixed(2),
          site: i.site,
        };
      });
      return list;
    }
    return res.data;
  } catch (e) {
    throw Error(e);
  }
};

const handleData = async (responses) => {
  const flattened = [].concat(...responses);
  flattened.sort((a, b) => a.customs_price - b.customs_price);
  const lowestCustomsPriceItem = flattened[0];
  return lowestCustomsPriceItem;
};

const getCountry = async () => {
  try {
    const res = await getCountryCurrency({
      pageSize: 1000,
      status: 1,
    });
    countryOptions.value = res.data;
  } catch (e) {
    throw Error(e);
  }
};

const handldSyncPlatformSite = async () => {
  console.log(formData.value);

  console.log(skuIndex.value);

  const goods_sku_recommended_platform = formData.value.goods_sku[
    skuIndex.value
  ]?.goods_sku_recommended_platform.filter((i) => !i.delete);
  if (goods_sku_recommended_platform.length == 0) {
    ElMessage.error("暂无可同步推荐平台/站点");
    return;
  }
  const new_goods_sku_recommended_platform = await getplatformSiteList(
    goods_sku_recommended_platform
  );

  ElMessageBox.confirm("是否获取推荐平台/站点信息，同步到清关信息。", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      mergeGoodsCustomsInfo(
        form.value.goods_sku_customs_info,
        new_goods_sku_recommended_platform
      );
    })
    .catch(() => {});
};

// 合并清关信息
const mergeGoodsCustomsInfo = (target, source) => {
  const sourceFilter = source
    .filter((supplier) => supplier.delete !== 1 && supplier.competitor_link)
    .map((item) => ({ ...item }));
  if (sourceFilter.length) {
    sourceFilter.forEach((sourceItem) => {
      let found = false;
      target.forEach((targetItem) => {
        if (
          targetItem.platform_id === sourceItem.platform_id &&
          targetItem.country_id === sourceItem.country_id
        ) {
          // 如果 country_id 和 platform_id 相同，则复制内容
          targetItem.customs_link = sourceItem.competitor_link;
          targetItem.customs_price = sourceItem.sales_price;
          targetItem.clearance_price = (
            Number(sourceItem.sales_price || 0) * 0.3
          ).toFixed(2);
          targetItem.customs_currency = sourceItem.currency_name;
          found = true;
        }
      });
      if (!found) {
        // 如果没有找到匹配项，则将 target 的元素推入 source
        console.log(sourceItem);
        const source_item = {
          platform_id: sourceItem.platform_id,
          platform_name: sourceItem.platform_name,
          country_id: sourceItem.country_id,
          country_name: sourceItem.country_name,
          customs_link: sourceItem.competitor_link,
          customs_price: sourceItem.sales_price,
          customs_currency: sourceItem.currency_name,
          clearance_price: (Number(sourceItem.sales_price || 0) * 0.3).toFixed(2),
        };
        target.push(source_item);
      }
    });

    return target;
  } else {
    return removeArrayIds(target);
  }
};

const getplatformSiteList = async (goods_sku_recommended_platform) => {
  const site_codes = goods_sku_recommended_platform.map((i) => i.site_code);

  try {
    const res = await getplatformSite({
      site_codes,
    });
    return goods_sku_recommended_platform.map((item) => {
      const site = res.data.find(
        (i) => i.platform_id == item.platform_id && i.site_code == item.site_code
      );
      console.log("site");
      console.log(site);

      if (site) {
        item.country_id = site.site_country_id;
        item.country_name = site.site_country_name;
      }
      return item;
    });
  } catch (e) {
    throw Error(e);
  }
};

// 下拉数据
const fetchOption = async () => {
  const res = await getOptions({
    name: ["goods.GoodsSkuCustom"],
  });
  options.value = res.data;
};

const computeBatteryName = (type) => {
  if (!type) {
    return "--";
  }
  const find = options.value["goods.GoodsSkuCustom"]?.[0].batteryTypeText.find(
    (i) => i.value == type
  );
  return find?.label || "--";
};

// 申报要素维护项 获取格式维护
const inputChange = async (val, item) => {
  const format = await matchingMaintenanceFormat(val);
  if (format) {
    const text = await getValue(item.text, item.value);
    item.value = text;
  } else {
    item.value = "";
  }
};

// 报关查询
const CustomsListRef = ref();
const handleCustomsSearch = () => {
  CustomsListRef.value.open({
    category: info.value.spu_category,
    customs_code: form.value.customs_code,
    supplier_id: info.value.supplier_id,
    supplier_name: info.value.supplier_name,
    id: form.value.id,
  });
};

// 选中报关信息
const selectCustoms = (selects) => {
  if (!selects) {
    return ElMessage.error("当前选中报关信息没有维护内容");
  }

  const filter_customs_info = form.value.goods_sku_customs_info
    .filter((i) => i.id)
    .map((j) => {
      j.delete = 1;
      return j;
    });

  const goods_sku_customs_info = [
    ...filter_customs_info,
    ...selects.goods_sku_customs_info.map((i) => {
      delete i.id;
      return i;
    }),
  ];

  if (goods_sku_customs_info.filter((i) => !i.delete).length == 0) {
    goods_sku_customs_info.push({
      customs_currency: "USD",
    });
  }
  form.value = {
    ...selects,
    goods_sku_customs_info,
    id: form.value.id,
  };
};

onMounted(() => {
  getCountry();
  fetchOption();
});
</script>
<style scoped>
:deep(.el-form-item--default) {
  margin-bottom: 5px;
}
</style>
